import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_1800/models/user.dart';
import 'package:flutter_1800/pages/goods/ConfirmOrder.dart';
import 'package:flutter_1800/pages/user/loginView.dart';
import 'package:flutter_1800/pages/widgets/MyButton.dart';
import 'package:flutter_1800/pages/widgets/MyNetImage.dart';
import 'package:flutter_1800/pages/widgets/MyText.dart';
import 'package:flutter_1800/service/api_service.dart';
import 'package:flutter_1800/tools/AppUtil.dart';
import 'package:flutter_1800/tools/config.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class GoodsDetail extends StatefulWidget {
  int id;

  GoodsDetail(this.id, {Key? key}) : super(key: key);

  @override
  _GoodsDetailState createState() => _GoodsDetailState();
}

class _GoodsDetailState extends State<GoodsDetail>
    with AutomaticKeepAliveClientMixin, RouteAware {
  Map? goods;

  int buyNum = 1;
  List images = [];
  List contentImages = [];

  double opacity = 0;
  Map? selectSpec;

  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    queryData();
    _scrollController.addListener(() {
      setState(() {
        opacity = _scrollController.position.pixels > 100
            ? 1
            : (_scrollController.position.pixels) / 100;
        if (opacity < 0) {
          opacity = 0;
        }
      });
    });
  }

  @override
  bool get wantKeepAlive => true;

  //回到当前页面
  @override
  void didPopNext() {
    queryData();
    print("返回了");
  }

  @override
  void didPop() {
    queryData();
  }

  void confirm() {
    // AppUtil.getTo(ConfirmOrder());
  }

  void submit() async {
    List orderDetails = [];

    orderDetails.add({
      "orderNo": "",
      "preOrderType": "",
      "productId": widget.id,
      "productNum": 1,
      "deskillId": 0,
      "shoppingCartId": 0
    });

    ApiService.preOrder({"goods": orderDetails, "userid": AppUtil.user!.id})
        .then((value) {
      AppUtil.getTo(ConfirmOrder(value));
    });

    //
  }

  void buy() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context1, setBottomSheetState) {
            return Container(
              padding: const EdgeInsets.all(15),
              height: 250,
              child: Column(
                children: [
                  GestureDetector(
                      onTap: () {
                        // var id = item["id"];
                        // NavigatorUtil.jump(
                        //     context, '/resourceDetail?id=$id');
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10)),
                        child: Row(
                          children: [
                            ClipRRect(
                              child: Image.network(
                                goods!["pic"],
                                width: 90,
                                height: 90,
                                fit: BoxFit.cover,
                              ),
                              borderRadius: BorderRadius.circular(10),
                            ),
                            const SizedBox(width: 5),
                            Expanded(
                                child: SizedBox(
                              height: 100,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  MyText(
                                    "¥" + goods!["money"],
                                    color: const Color(0xffF44453),
                                    fontSize: 20,
                                    weight: FontWeight.bold,
                                  ),
                                  const SizedBox(
                                    height: 10,
                                  ),
                                  Container(
                                    padding:
                                        const EdgeInsets.fromLTRB(10, 5, 10, 5),
                                    decoration: BoxDecoration(
                                        color: Colors.red,
                                        borderRadius:
                                            BorderRadius.circular(20)),
                                    child: MyText(
                                      "送" + goods!["give_coin"] + "趣豆",
                                      color: Colors.white,
                                      fontSize: 15,
                                    ),
                                  )
                                ],
                              ),
                            ))
                          ],
                        ),
                      )),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      MyText(
                        "数量",
                        fontSize: 15,
                      ),
                      Container(
                        child: Row(
                          children: [
                            GestureDetector(
                              onTap: () {
                                setBottomSheetState(() {
                                  buyNum = buyNum - 1;
                                  if (buyNum < 1) {
                                    buyNum = 1;
                                  }
                                });
                              },
                              child: Container(
                                child: MyText("-"),
                                padding:
                                    const EdgeInsets.fromLTRB(12, 8, 12, 8),
                                decoration: BoxDecoration(
                                    borderRadius: const BorderRadius.only(
                                        bottomLeft: Radius.circular(20),
                                        topLeft: Radius.circular(20)),
                                    border: Border.all(
                                        color: const Color(0xffD9D9D9))),
                              ),
                            ),
                            Container(
                              child: MyText(buyNum.toString()),
                              padding: const EdgeInsets.all(8),
                              decoration: const BoxDecoration(
                                  border: Border(
                                top: BorderSide(
                                    width: 1.0, color: Color(0xffD9D9D9)),
                                bottom: BorderSide(
                                    width: 1.0, color: Color(0xffD9D9D9)),
                              )),
                            ),
                            GestureDetector(
                                onTap: () {
                                  setBottomSheetState(() {
                                    buyNum = buyNum + 1;
                                  });
                                },
                                child: Container(
                                  child: MyText("+"),
                                  padding:
                                      const EdgeInsets.fromLTRB(12, 8, 12, 8),
                                  decoration: BoxDecoration(
                                      borderRadius: const BorderRadius.only(
                                          topRight: Radius.circular(20),
                                          bottomRight: Radius.circular(20)),
                                      border: Border.all(
                                          color: const Color(0xffD9D9D9))),
                                )),
                          ],
                        ),
                      )
                    ],
                  ),
                  const SizedBox(height: 20),
                  MyButton(
                    "确定",
                    width: 200,
                    onTap: () {
                      confirm();
                    },
                  )
                ],
              ),
            );
          });
        });
  }

  void popSpecChoose(bool buy) {
    User? user = AppUtil.user;
    if (user == null) {
      AppUtil.replace(LoginViewPage());
      return;
    }

    List specs = goods!["specitems"];
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context1, setBottomSheetState) {
            return Container(
              padding: const EdgeInsets.all(15),
              constraints: const BoxConstraints(maxHeight: 500),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(8),
                          child: MyNetImage(
                            url: images[0],
                            width: 100,
                            height: 100,
                          ),
                        ),
                        const SizedBox(
                          width: 10,
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            MyText(goods!["title"]),
                            const SizedBox(height: 50),
                            MyText(
                              "¥" +
                                  (selectSpec == null
                                      ? goods!["minprice"].toString()
                                      : selectSpec!["price"].toString()),
                              color: Colors.red,
                              fontSize: 20,
                              weight: FontWeight.bold,
                            )
                          ],
                        ),
                        const Spacer(),
                        IconButton(
                            onPressed: () {
                              AppUtil.back();
                            },
                            icon: const Icon(
                              Icons.close,
                              color: AppConfig.font2,
                            ))
                      ],
                    ),
                    const SizedBox(height: 20),
                    ...specs.map((e) {
                      return GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          setState(() {
                            selectSpec = e;
                          });
                          setBottomSheetState(
                            () => {},
                          );
                        },
                        child: Container(
                          padding: const EdgeInsets.all(10),
                          margin: const EdgeInsets.only(bottom: 10),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color: selectSpec == e
                                  ? AppConfig.themeDeepColor
                                  : const Color(0xfff5f5f5)),
                          child: Row(
                            children: [
                              MyText(
                                e["name"],
                                color: selectSpec == e
                                    ? Colors.white
                                    : AppConfig.font2,
                              ),
                              const Spacer(),
                              MyText(
                                "¥" + e["price"].toString(),
                                color: selectSpec == e
                                    ? Colors.white
                                    : AppConfig.font2,
                              ),
                            ],
                          ),
                        ),
                      );
                    }),
                    MyButton(
                      "确定",
                      width: double.infinity,
                      onTap: () {
                        if (buy) {
                          confirm();
                          //   結算
                        } else {
                          addCart();
                        }
                      },
                    ),
                    const SizedBox(height: 20),
                  ],
                ),
              ),
            );
          });
        });
  }

  ///see AutomaticKeepAliveClientMixin

  void queryData() {
    ApiService.goodsDetails(widget.id).then((value) {
      setState(() {
        goods = value;
        contentImages = jsonDecode(goods!["detail"]);
        images = goods!["images"].toString().split(",");
      });
    });
  }

  void addCart() async {
    User? user = AppUtil.user;
    if (user == null) {
      AppUtil.getTo(const LoginViewPage());
      return;
    }
    ApiService.addCart(
      widget.id,
      user.id,
      1,
      selectSpec!["id"],
      selectSpec!["name"],
      selectSpec!["price"].toDouble(),
      selectSpec!["unit"],
    ).then((value) {
      EasyLoading.showSuccess("加入成功");
      AppUtil.back();
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    double itemWidth =
        (MediaQuery.of(context).size.width - AppUtil.getPadding() * 2 - 10) / 2;
    double itemHeight = itemWidth + 50;

    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          shadowColor: Colors.transparent,
          backgroundColor:
              Color.fromARGB((opacity * 255).toInt(), 255, 255, 255),
          systemOverlayStyle: SystemUiOverlayStyle.dark
              .copyWith(statusBarColor: Colors.transparent),
          centerTitle: true,
          elevation: 0.0,
          toolbarHeight: 40,
          titleSpacing: 0,
          title: Container(
            width: double.infinity,
            height: 50,
            alignment: Alignment.center,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(
                    child: Opacity(
                        opacity: opacity,
                        child: MyText(
                          goods != null ? goods!["title"] : "商品详情",
                        ))),
                IconButton(
                  icon: Icon(
                    Icons.more_horiz,
                    color: Color.fromARGB(
                        255,
                        (255 - opacity * 255).toInt(),
                        (255 - opacity * 255).toInt(),
                        (255 - opacity * 255).toInt()),
                    size: 16,
                  ),
                  onPressed: () {
                    AppUtil.back();
                  },
                )
              ],
            ),
          ),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              color: Color.fromARGB(255, (255 - opacity * 255).toInt(),
                  (255 - opacity * 255).toInt(), (255 - opacity * 255).toInt()),
              size: 16,
            ),
            onPressed: () {
              AppUtil.back();
            },
          ),
        ),
        backgroundColor: AppConfig.grayBgColor,
        body: Column(
          children: [
            Expanded(
                child: goods == null
                    ? Container()
                    : SingleChildScrollView(
                        physics: const BouncingScrollPhysics(),
                        controller: _scrollController,
                        child: Column(
                          children: [
                            SizedBox(
                              width: double.infinity,
                              height: MediaQuery.of(context).size.width * 1,
                              child: Swiper(
                                itemHeight:
                                    MediaQuery.of(context).size.width * 0.5,
                                itemBuilder: (BuildContext context, int index) {
                                  String item = images[index];
                                  return Container(
                                    height: double.infinity,
                                    width: double.infinity,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(10),
                                        color: Colors.black),
                                    child: MyNetImage(
                                      url: item,
                                      fit: BoxFit.cover,
                                    ),
                                  );
                                },
                                scale: 0.8,
                                itemCount: images.length,
                                autoplay: false,
                                pagination: null, //这些都是控件默认写好的,直接用
                              ),
                            ),
                            Container(
                              padding: const EdgeInsets.all(10),
                              width: double.infinity,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(10)),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      MyText(
                                        "¥" + goods!["minprice"].toString(),
                                        color: const Color(0xffF44453),
                                        maxLines: 1,
                                        fontSize: 18,
                                        weight: FontWeight.bold,
                                      ),
                                      MyText(
                                        goods!["buynum"].toString() + "人已购买",
                                        color: const Color(0xffAFAFAF),
                                        fontSize: 12,
                                        maxLines: 1,
                                      ),
                                    ],
                                  ),
                                  const SizedBox(height: 10),
                                  MyText(
                                    goods!["title"],
                                    color: AppConfig.font1,
                                    fontSize: 18,
                                    maxLines: 1,
                                    weight: FontWeight.bold,
                                  ),
                                  // const SizedBox(height: 5),
                                ],
                              ),
                            ),
                          ],
                        ),
                      )),
            Container(
              padding: EdgeInsets.fromLTRB(
                  AppUtil.getPadding(),
                  AppUtil.getPadding(),
                  AppUtil.getPadding(),
                  AppUtil.getPadding() + MediaQuery.of(context).padding.bottom),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(30),
                    child: Row(
                      children: [
                        InkWell(
                          onTap: () {
                            popSpecChoose(false);
                          },
                          child: Container(
                            padding: const EdgeInsets.all(10),
                            decoration: const BoxDecoration(
                                gradient: LinearGradient(
                                    begin: Alignment.topLeft,
                                    end: Alignment.bottomRight,
                                    colors: [
                                  Color(0xffe0e8fd),
                                  Color(0xffe0e8fd)
                                ])),
                            child: MyText(
                              "加入购物车",
                              color: const Color(0xff6b8fd3),
                              fontSize: 15,
                            ),
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            )
          ],
        ));
  }
}
